package cn.xiaolang.function.file_manage;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 深入调研文件IO
 *
 * @author Dean
 * @date 2022/4/4
 */
public class FileIOStarted {

    public static void main(String[] args) throws Exception {
        String filePath = "./temp.txt";
        byte[] defaultData = "hello dean\n".getBytes();
        if (!Objects.isNull(args) && args.length > 0) {
            if ("0".equals(args[0])) {
                fileOutputStreamIOTest(filePath, defaultData);
            } else if ("1".equals(args[0])) {
                bufferedFileIOTest(filePath, defaultData);
            }
        }
    }


    private static void fileOutputStreamIOTest(String filePath, byte[] defaultData)
            throws Exception {
        File file = new File(filePath);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        while (true) {
            TimeUnit.MILLISECONDS.sleep(10);
            fileOutputStream.write(defaultData);
        }
    }

    // jvm 8KB syscall write 8KB byte[]
    private static void bufferedFileIOTest(String filePath, byte[] defaultData)
            throws Exception {
        File file = new File(filePath);
        BufferedOutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(file));
        while (true) {
            TimeUnit.MILLISECONDS.sleep(10);
            fileOutputStream.write(defaultData);
        }
    }
}
